import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';

export 'package:connectivity_plus/connectivity_plus.dart' show ConnectivityResult;

/// 网络连通检查
class ConnectivityUtils {
  /// 工厂模式
  factory ConnectivityUtils() => _getInstance();

  /// 单例
  static ConnectivityUtils get instance => _getInstance();
  static ConnectivityUtils? _instance;

  /// 网络链接,这个在内部实现也是单利来的
  final Connectivity _connectivity = Connectivity();

  /// 存储的网络连接监听器
  final Map<String, StreamSubscription<ConnectivityResult>> _connectivitySubscription = {};

  ConnectivityUtils._internal();

  static ConnectivityUtils _getInstance() => _instance ??= ConnectivityUtils._internal();

  /// 获取当前网络状态
  Future<ConnectivityResult> get checkConnectivity async => await _connectivity.checkConnectivity();

  /// 注册监听事件
  bool monitoring(String listenerName, Function(ConnectivityResult) onData) {
    if (!_connectivitySubscription.containsKey(listenerName)) {
      _connectivitySubscription[listenerName] = _connectivity.onConnectivityChanged.listen(onData);
      return true;
    }
    throw ExistListenerNameException("There are the same listener name, please check again");
  }

  /// 取消监听
  void unMonitor(String listenerName) {
    if (_connectivitySubscription.containsKey(listenerName)) {
      _connectivitySubscription[listenerName]!.cancel();
      _connectivitySubscription.remove(listenerName);
    }
  }

  /// 取消注册
  void destroy() {
    if (_connectivitySubscription.length > 0) {
      _connectivitySubscription.forEach((key, element) => element.cancel());
      _connectivitySubscription.clear();
    }
  }
}

class ExistListenerNameException implements Exception {
  final String message;

  ExistListenerNameException(this.message);

  String toString() {
    Object? message = this.message;
    return "ExistListenerNameException: $message";
  }
}
